package com.sykj.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sykj.dao.CategoryDao;
import com.sykj.pojo.Category;
import com.sykj.servies.CategoryServies;
import com.sykj.servies.ProductServies;
import com.sykj.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("category")
public class CategoryController {
    //商品分类
    @Autowired
    CategoryServies categoryServies;
    @Autowired
    ProductServies productServies;
    @RequestMapping("/list")
    public String list(Model model, Page page){
        //分页查询
        PageHelper.offsetPage(page.getStart(),page.getCount());
        //查询商品的分类
        List<Category> list = categoryServies.list();
        //总条数
        int total = (int) new PageInfo<>(list).getTotal();
        page.setTotal(total);
        model.addAttribute("list",list);
        model.addAttribute("total",total);
        model.addAttribute("size",list.size());
        return "productmodule/category-list";
    }

    //点击添加商品类型，弹出layue框
    @RequestMapping("/addCategory")
    public String add(@RequestParam(value = "name")String name){
        Category category = new Category();
        //拿到添加的商品类名
        category.setName(name);
        categoryServies.save(category);
        return "productmodule/category-list";
    }

    //删除分类，根据id删除
    @RequestMapping("/delCategory")
    //删除，如果该分类下有商品，那就不能删除
    public String del(@RequestParam(value = "id")int id, Model model, HttpSession session,Page page){
        boolean cunzai=productServies.findProByCid(id);
       if(!cunzai){
            categoryServies.del(id);
       }
        return "redirect:list";

    }
    //点击分类编辑,修改
    @RequestMapping("/editCategory")
    public String edit(@RequestParam(value = "id")int id,Model model){
        //根据id修改===得到单个分类的id
        Category category = categoryServies.get(id);
        model.addAttribute("category",category);
        return "productmodule/category-edit";
    }
    //修改商品类型
    @RequestMapping("/updateCategory")
    public String update(Category category,Model model){
        categoryServies.update(category);
        //返回到当前页，刷新
        return "redirect:list";
    }

}
